/**
 * Login-App Token工具类
 * 专门用于处理微前端架构下的token管理
 */

/**
 * 设置token到cookie
 */
export const setTokenToCookie = (token: string, userInfo?: any): void => {
  if (!token) {
    return;
  }

  try {
    const expires = new Date();
    expires.setTime(expires.getTime() + 7 * 24 * 60 * 60 * 1000); // 7天

    // 保存token到cookie
    document.cookie = `token=${encodeURIComponent(token)}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
    console.log('🍪 [LoginApp] Token saved to cookie:', `${token.substring(0, 20)}...`);

    // 保存用户信息到cookie
    if (userInfo) {
      const userInfoStr = encodeURIComponent(JSON.stringify(userInfo));
      document.cookie = `user_info=${userInfoStr}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
      console.log('👤 [LoginApp] User info saved to cookie');
    }

    // 设置登录成功标记
    document.cookie = `login_success=true; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
    console.log('✅ [LoginApp] Login success flag set');
  } catch (error) {
    console.error('❌ [LoginApp] Failed to save token to cookie:', error);
  }
};

/**
 * 从cookie获取token
 */
export const getTokenFromCookie = (): string => {
  try {
    const cookieStr = document.cookie;
    if (!cookieStr) {
      return '';
    }

    const cookies = cookieStr.split(';');
    for (const cookie of cookies) {
      const trimmedCookie = cookie.trim();
      if (!trimmedCookie) continue;

      const [name, value] = trimmedCookie.split('=');
      if (name === 'token' && value) {
        try {
          const decodedToken = decodeURIComponent(value);
          if (decodedToken && decodedToken.length > 10) {
            console.log('🔑 [LoginApp] Token retrieved from cookie:', `${decodedToken.substring(0, 20)}...`);
            return decodedToken;
          }
        } catch (e) {
          console.warn('Failed to decode token from cookie:', e);
          if (value && value.length > 10) {
            return value;
          }
        }
      }
    }
  } catch (error) {
    console.warn('⚠️ [LoginApp] Failed to get token from cookie:', error);
  }

  return '';
};

/**
 * 清理所有cookie
 */
export const clearAllCookies = (): void => {
  try {
    // 清理token相关cookie
    const cookiesToClear = ['token', 'user_info', 'login_success'];
    cookiesToClear.forEach((cookieName) => {
      document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
    });

    console.log('🧹 [LoginApp] All cookies cleared');
  } catch (error) {
    console.error('❌ [LoginApp] Failed to clear cookies:', error);
  }
};

/**
 * 检查cookie中是否有登录信息
 */
export const hasLoginCookie = (): boolean => {
  const token = getTokenFromCookie();
  return !!(token && token.length > 10);
};
